﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace IdentityServer
{
    public static class ConsulHelper
    {
        public static void AddConsulService(this IServiceCollection services, IConfiguration configuration)
        {
            ConfigConsul(configuration);
        }

        public static void UseConsulService(this IApplicationBuilder app, IConfiguration configuration)
        {
            ConfigConsul(configuration);
        }

        private static void ConfigConsul(IConfiguration configuration)
        {
            var serviceName = Assembly.GetExecutingAssembly().GetName().Name;
            ConsulClient client = new ConsulClient(options =>
            {
                options.Address = new Uri(configuration["Consul:Address"]);////请求注册的 Consul 地址
                options.Datacenter = configuration["Consul:DataCenter"];
            });

            string Weight = configuration["Consul:Weight"];

            //命令行参数
            string localAddr = configuration["ip"];
            int port = int.Parse(configuration["port"]);
            string healthUrl = $"http://{localAddr}:{port}{configuration["Consul:CheckUrl"]}";
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = serviceName + port,//唯一编号
                Name = serviceName,//组名,分组名称
                Address = localAddr,//健康检查地址，本机地址
                Port = port,
                Tags = new string[] { Weight, "name=jetydu" },
                Check = new AgentServiceCheck()
                {
                    DeregisterCriticalServiceAfter = TimeSpan.FromMilliseconds(1000), //服务停止后多久注销
                    Interval = TimeSpan.FromSeconds(5), //服务健康检查间隔
                    Timeout = TimeSpan.FromSeconds(5), //检查超时的时间
                    HTTP = healthUrl////健康检查地址
                }
            });
        }
    }
}
